package com.common.sms.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.common.sms.exception.SmsBaseException;
import com.common.sms.config.SmsConfig;
import com.common.sms.instance.SmsInstance;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 牧鱼
 * @Classname SmsSendService
 * @Description TODO
 * @Date 2021/5/5
 */
@Service
public class SmsSendService {

    /**
     * 短信服务对象
     */
    private Client smsClient;

    /**
     * 短信签名
     */
    private String signName;

    public SmsSendService(SmsInstance smsInstance , SmsConfig smsConfig) {
        this.smsClient = smsInstance.getSmsClient();
        this.signName = smsConfig.getSignName();
    }

    /**
     * 发送单条短信
     * @param tel
     * @param templateCode
     * @param sendDataMap
     */
    public String sendSms(String tel , String templateCode , Map<String,String> sendDataMap){
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(tel)
                .setSignName(this.signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(JSONObject.toJSONString(sendDataMap));
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = smsClient.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsBaseException(e.getMessage());
        }
        return JSONObject.toJSONString(sendSmsResponse.getBody());
    }

    public String sendBatchSms(List<String> telList , String templateCode , List<Map<String,String>> sendDataList ){
        SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest()
                .setPhoneNumberJson(JSONObject.toJSONString(telList))
                .setSignNameJson(JSONObject.toJSONString(new ArrayList<String>(){{
                    for (String s : telList) {
                        add(signName);
                    }
                }}))
                .setTemplateCode(templateCode)
                .setTemplateParamJson(JSONObject.toJSONString(sendDataList))
                ;
        SendBatchSmsResponse sendBatchSmsResponse = null;
        try {
            sendBatchSmsResponse = this.smsClient.sendBatchSms(sendBatchSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsBaseException(e.getMessage());
        }
        return JSONObject.toJSONString(sendBatchSmsResponse.getBody());
    }

}
